<?php
namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\model\Erp;
use think\Db;
/**
*   用户注册的时候同步到erp中的信息
*/

class Register extends Command
{
    protected function configure()
    {
        $this->setName('Register')->setDescription("定时获取新用户，同步ERP数据到本后台");
    }

    protected function execute(Input $input, Output $output)
    {

        $output->writeln('定时命令开始执行...');
        

        //先获取绑定了手机并且有openid 的用户，审核状态为0 的 10 个最新用户信息列表
        $list = \think\Db::table('d_users')
            ->where('status', 0)    
            ->where('openid','not null')
            ->where('phone','not null')
            ->field('id, truename, phone, openid, gender')
            ->order('id DESC')
            ->limit(10)
            ->select();
        $output->writeln('有数据了');
        //循环梳理数据
        foreach ($list as $key => $value) {
            $arr = [
                'MOBIL' => $value['phone'],
                'VIPNAME' => $value['truename'],
                'VIPTYPE' => '',
                'OPENID' => $value['openid'],
                'SEX' => $value['gender'] == 1 ? 'M' : 'W',
                'VALIDDATE' => '',
            ];
            $output->writeln('这里？');
            $erp = new Erp();
            $output->writeln('这里？111');
            $res = $erp->register($arr);
            $output->writeln('这里？11122');
            // $output->writeln(Pdo::errorCode());
            //erp 返回的数据
            $erp_arr = json_decode($res[0]['RES'], 1);

            //判断是否成功
            if($erp_arr['IFSUCESS'] == 'Y'){
                //erp 操作成功，修改本地数据，：修改绑定erp中返回的会员编号

                //返回erp 上的注册时间，同步修改club 的注册和修改时间
                $map = [
                    'vip_number' => $erp_arr['VIPCARD'],
                    'create_at' => strtotime($erp_arr['MODIFIEDDATE']),
                    'modify_time' => strtotime($erp_arr['MODIFIEDDATE']),
                    'status' => 3,
                ];

                $up_user = \think\Db::table('d_users')
                    ->where('id', $value['id'])
                    ->update($map);

                $this->add_log($erp_arr['message'], $erp_arr['IFSUCESS']);
            } else{
                //错误写入日志
                $this->add_log($erp_arr['message'], $erp_arr['IFSUCESS']);
            }
            // dump(json_decode($res[0]['RES'], 1));exit;
        }

        $output->writeln('定时命令执行已经结束...');
    }

    /**
    *   日志
    *   content    内容
    *   status    状态：Y/N
    */
    public function add_log($content, $status)
    {
        $data = [
            'content' => $content,
            'status' => $status,
            'create_at' => time()
        ];

        $res = \think\Db::table('d_erp_syn_log')->insert($data);

        return $res;
    }
}